﻿<!DOCTYPE html>
<html>
<head>
    <title>Index</title>
    <script src="/lib/jquery/1.12.4/jquery.min.js"></script>
    <script src="/lib/bootstrap/3.3.7/js/bootstrap.js"></script>
    <link href="/lib/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet" />
    <link href="/lib/font-awesome/4.7.0/css/font-awesome.css" rel="stylesheet" />
    <link href="/css/framework-style.css" rel="stylesheet" />
    <script src="/lib/art-template/lib/template-web.js"></script>
    @*<link href="~/lib/jqPaginator/dist/jqpaginator.min.css" rel="stylesheet" />
    <script src="~/lib/jqPaginator/dist/jqpaginator.min.js"></script>*@
    <script src="~/lib/nestable/jquery.nestable.js"></script>
    <script src="/js/framework-ui.js"></script>

    <style type="text/css">

    </style>
</head>
<body class="gray-bg">
    <div class="wrapper wrapper-content  animated fadeInRight">
        <div class="row">
            <div class="col-sm-5">
                <div class="ibox ">
                    <div class="ibox-title">
                        <h5>菜单管理</h5>
                        <div class="ibox-tools">
                            <a href="javascript:void(0);" id="btnAddFirstMenu" class="btn btn-primary btn-xs">添加一级菜单</a>
                            <a href="javascript:void(0);" id="btnUpdateWxMenu" class="btn btn-primary btn-xs">更新微信菜单</a>
                        </div>
                    </div>
                    <div class="ibox-content">
                        <div class="dd" id="nestable">
                            <ol class="dd-list"></ol>
                        </div>
                        <div class="m-t-md">
                            <h5>数据：</h5>
                        </div>
                        <textarea id="nestable-output" class="form-control" rows="5"></textarea>
                    </div>
                </div>
            </div>
            <div class="col-sm-7">
                <div class="ibox float-e-margins">
                    <div class="ibox-title">
                        <h5>按钮其他参数 </h5>
                    </div>
                    <div class="ibox-content" style="min-height: 630px;">
                        <div class="form-horizontal">
                            <div id="menuBtnGroup" class="btn-group">
                                <button id="btn_click" class="btn btn-white" data-menutype="click" data-menutmpl="keyTemplate"><i class="fa fa-font"></i>&nbsp;<span>点击推事件</span></button>
                                <button id="btn_view" class="btn btn-white" data-menutype="view" data-menutmpl="urlTemplate"><i class="fa fa-link"></i>&nbsp;<span>跳转URL</span></button>
                                <button id="btn_scancode_push" class="btn btn-white" data-menutype="scancode_push" data-menutmpl="keyTemplate"><i class="fa fa-qrcode"></i>&nbsp;<span>扫码推事件</span></button>
                                <button id="btn_scancode_waitmsg" class="btn btn-white" data-menutype="scancode_waitmsg" data-menutmpl="keyTemplate"><i class="fa fa-qrcode"></i>&nbsp;<span>扫码推事件且弹出“消息接收中”提示框"</span></button>
                                <button id="btn_pic_sysphoto" class="btn btn-white" data-menutype="pic_sysphoto" data-menutmpl="keyTemplate"><i class="fa fa-camera"></i>&nbsp;<span>弹出系统拍照发图</span></button>
                                <button id="btn_pic_photo_or_album" class="btn btn-white" data-menutype="pic_photo_or_album" data-menutmpl="keyTemplate"><i class="fa fa-camera"></i>&nbsp;<span>弹出拍照或者相册发图</span></button>
                                <button id="btn_pic_weixin" class="btn btn-white" data-menutype="pic_weixin" data-menutmpl="keyTemplate"><i class="fa fa-picture-o"></i>&nbsp;<span>弹出微信相册发图器</span></button>
                                <button id="btn_location_select" class="btn btn-white" data-menutype="location_select" data-menutmpl="keyTemplate"><i class="fa fa-map-marker"></i>&nbsp;<span>弹出地理位置选择器</span></button>
                                <button id="btn_media_id" class="btn btn-white" data-menutype="media_id" data-menutmpl="materialTemplate"><i class="fa fa-newspaper-o"></i>&nbsp;<span>下发消息（除文本消息）</span></button>
                                <button id="btn_view_limited" class="btn btn-white" data-menutype="view_limited" data-menutmpl="newsTemplate"><i class="fa fa-envelope"></i>&nbsp;<span>跳转图文消息URL</span></button>
                            </div>
                            @*<div id="description" class="well">
                                    点击推事件用户点击click类型按钮后，微信服务器会通过消息接口推送消息类型为event的结构给开发者（参考消息接口指南），并且带上按钮中开发者填写的key值，开发者可以通过自定义的key值与用户进行交互；
                                </div>*@
                            <div class="hr-line-dashed"></div>
                            <div class="form-group">
                                <label class="col-sm-2 control-label" for="name">名称</label>
                                <div class="col-sm-10">
                                    <input id="name" type="text" class="form-control" required="required">
                                </div>
                            </div>
                            <div id="menuBtnTemplate">

                            </div>
                            <div class="hr-line-dashed"></div>
                            <div class="form-group">
                                <div class="col-sm-4 col-sm-offset-2">
                                    <button id="btn_save" class="btn btn-primary">保存内容</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script>
        var menuObj = {
            menu: {},
            conditionalmenu: {}
        }
        $(function () {
            $('#menuBtnGroup').find('button').bind('click', function () {
                $('input:required').each(function (i, o) {
                    $(o).parent().parent().removeClass('has-error');
                    $(o).parent().parent().removeClass('has-success');
                })

                $('#menuBtnGroup').find('button').each(function (index, element) {
                    if ($(element).hasClass('btn-primary')) {
                        $(element).removeClass('btn-primary');
                        $(element).removeClass('btn-selected');
                        $(element).addClass('btn-white');
                    }
                })
                if ($(this).hasClass('btn-white')) {
                    $(this).removeClass('btn-white');
                    $(this).addClass('btn-primary');
                    $(this).addClass('btn-selected');
                }

                var menuType = $(this).attr('data-menutype');
                var menuTmpl = $(this).attr('data-menutmpl');
                $('#menuBtnTemplate').empty();
                $('#menuBtnTemplate').html(template(menuTmpl, {}));
                $('#name').val($(".dd-item-selected").attr('data-name'));
                if (menuType == 'view') {
                    $('#url').val($(".dd-item-selected").attr('data-url'));
                    $('#url').unbind('change');
                    $('#url').bind('change', function () {
                        if ($(this).val().trim() != '') {
                            $(this).closest('.form-group').removeClass('has-error');
                        }
                    })
                }
                else if (menuType == 'media_id') {
                    $('#media_id').val($(".dd-item-selected").attr('data-mediaid'));
                    $('#choose-material').unbind();
                    $('#choose-material').bind('click', function () {
                        $.modalOpen({
                            id: "Choose",
                            title: "选择素材",
                            url: '/WeixinManage/WxMaterial/Choose', //iframe的url
                            width: "90%",
                            height: "90%",
                            callBack: function (iframeId) {
                                top.frames['Choose'].submitForm();
                                if (top.tempData != '') {
                                    var jsonObj = JSON.parse(top.tempData);
                                    $('#media_id').val(jsonObj.MediaId);
                                }
                            }
                        });
                    });
                }
                else if (menuType == 'view_limited') {
                    $('#media_id').val($(".dd-item-selected").attr('data-mediaid'));
                    $('#choose-news').unbind();
                    $('#choose-news').bind('click', function () {
                        $.modalOpen({
                            id: "Choose",
                            title: "选择图文素材",
                            url: '/WeixinManage/WxNews/Choose', //iframe的url
                            width: "90%",
                            height: "90%",
                            callBack: function (iframeId) {
                                top.frames['Choose'].submitForm();
                                if (top.tempData != '') {
                                    var jsonObj = JSON.parse(top.tempData);
                                    $('#media_id').val(jsonObj.MediaId);
                                }
                            }
                        });
                    });
                }
                else {
                    $('#key').val($(".dd-item-selected").attr('data-key'));
                    $('#key').unbind('change');
                    $('#key').bind('change', function () {
                        if ($(this).val().trim() != '') {
                            $(this).closest('.form-group').removeClass('has-error');
                        }
                    })
                }
            });

            $('#btnAddFirstMenu').bind('click', function () {
                if ($('.first-menu').length < 3) {
                    $('#nestable').find('ol').eq(0).append(template('firstMenuTemplate', {}));
                    bindNestableEvents();
                    $('.first-menu:last').find('.btnEdit')[0].click();
                    //$('#btn_click').click();
                }
                else {
                    $.modalAlert('自定义菜单最多包括3个一级菜单，每个一级菜单最多包含5个二级菜单。','warning');
                }
            });
            $('#btn_save').bind('click', function () {
                if ($(".dd-item-selected").length == 0) {
                    $.modalAlert('请先选择需要编辑的菜单项目。', 'warning');
                    return false;
                }
                if (!validData()) {
                    return false;
                }
                var menuType = $('.btn-selected').attr('data-menutype');
                $(".dd-item-selected").attr('data-name', $('#name').val());
                $(".dd-item-selected").find('span')[1].innerText = $('#name').val();
                if (typeof (menuType) != 'undefined') {
                    $(".dd-item-selected").attr('data-type', menuType);
                    if (menuType == 'view') {
                        $('.dd-item-selected').attr('data-url', $('#url').val());
                    }
                    else if (menuType == 'media_id') {
                        $('.dd-item-selected').attr('data-mediaid', $('#media_id').val());
                    }
                    else if (menuType == 'view_limited') {
                        $('.dd-item-selected').attr('data-mediaid', $('#media_id').val());
                    }
                    else {
                        $('.dd-item-selected').attr('data-key', $('#key').val());
                    }
                }
            });
            $.ajax({
                url: "/WeixinManage/WxMenu/GetFormJson",
                data: {},
                dataType: "json",
                async: false,
                success: function (result) {
                    //if (result == null) {
                    //    //document.getElementById('template').innerHTML = template('click_template', {});
                    //}
                    //else {
                    //    var menuData = result.MenuData.replace("\\", "");
                    //    menuJson = JSON.parse(menuData);
                    //    $('#nestable').find('ol').eq(0).html(template('nestableTemplate', menuJson.menu));
                    //    bindNestableEvents();
                    //    //$('.first-menu:first').find('.btnEdit')[0].click();
                    //    //$('#btn_click').click();
                    //}
                    if (result.MenuData != null) {
                        var menuData = result.MenuData.replace("\\", "");
                        menuJson = JSON.parse(menuData);
                        $('#nestable').find('ol').eq(0).html(template('nestableTemplate', menuJson.menu));
                        bindNestableEvents();
                    }
                    $('#nestable').nestable({ maxDepth: 2 });
                }
            });
            $('#btnUpdateWxMenu').bind('click', function () {
                var menu = {
                    button: []
                };
                $('#nestable').find('.first-menu').each(function (index, element) {
                    var object = {}
                    var firstType = $(element).attr('data-type');
                    var firstName = $(element).attr('data-name');
                    var secondMenus = $(element).find('.second-menu')
                    if (secondMenus.length > 0) {
                        object.name = firstName;
                        object.sub_button = [];
                        $(element).find('.second-menu').each(function (idx, ele) {
                            var obj = {};
                            var secondType = $(ele).attr('data-type');
                            var secondName = $(ele).attr('data-name');
                            obj.name = secondName;
                            obj.type = secondType;
                            if (secondType == 'view') {
                                obj.url = $(ele).attr('data-url');
                            }
                            else if (secondType == 'media_id') {
                                obj.media_id = $(ele).attr('data-mediaid');
                            }
                            else if (secondType == 'view_limited') {
                                obj.media_id = $(ele).attr('data-mediaid');
                            }
                            else {
                                obj.key = $(ele).attr('data-key');
                            }
                            obj.sub_button = [];
                            object.sub_button.push(obj);
                        });
                        menu.button.push(object);
                    }
                    else {
                        object.name = firstName;
                        object.type = firstType;
                        if (firstType == 'view') {
                            object.url = $(element).attr('data-url');
                        }
                        else if (firstType == 'media_id') {
                            object.media_id = $(element).attr('data-mediaid');
                        }
                        else if (firstType == 'view_limited') {
                            object.media_id = $(element).attr('data-mediaid');
                        }
                        else {
                            object.key = $(element).attr('data-key');
                        }
                        object.sub_button = [];
                        menu.button.push(object);
                    }
                });
                menuObj.menu = menu;
                console.log(menuObj);
                $('#nestable-output').val(JSON.stringify(menuObj));
                $.ajax({
                    url: '/WeixinManage/WxMenu/SubmitForm',
                    data: { menuData: JSON.stringify(menuObj) },
                    type: "Post",
                    dataType: "json",
                    success: function (result) {
                        if (result.state == 'success') {
                            $.modalMsg(result.message, 'success');
                        }
                        else {
                            $.modalAlert(result.message, 'error');
                        }
                    }
                });
            });

            $('#name').bind('change', function () {
                if ($(this).val().trim() != '') {
                    $(this).closest('.form-group').removeClass('has-error');
                }
            })
            $('#key').bind('change', function () {
                if ($(this).val().trim() != '') {
                    $(this).closest('.form-group').removeClass('has-error');
                }
            })
        });

        function bindNestableEvents() {
            $('.dd-handle').unbind();
            $('.dd-handle').bind('mousedown', function (e) {
                e.stopPropagation();
            });

            $('.btnAdd').unbind();
            $('.btnAdd').bind('click', function (event) {
                if ($(this).parent().next().find('.second-menu').length < 5) {
                    $(this).parent().next().append(template('secondMenuTemplate', {}));
                    $('#nestable').nestable({ maxDepth: 2 });
                    bindNestableEvents();
                    $(this).parent().next().find('.btnEdit:last')[0].click();
                    $('#btn_click').click();
                }
                else {
                    $.modalAlert('自定义菜单最多包括3个一级菜单，每个一级菜单最多包含5个二级菜单。','warning');
                }
            });

            $('.btnEdit').unbind();
            $('.btnEdit').bind('click', function (event) {
                $('.dd-handle').css('border', '1px solid #e7eaec');
                $(this).parent().css('border', '2px solid #1ABC9C');
                $('.dd-item').removeClass('dd-item-selected');
                $(this).parent().parent().addClass('dd-item-selected');
                
                $('#name').val($('.dd-item-selected').attr('data-name'));
                $('#menuBtnTemplate').empty();
                
                var li = $(this).closest('li');
                var type = li.attr('data-type');
                if (typeof (type) == 'undefined'||type == '') {
                    $('#menuBtnGroup').find('button').each(function (index, element) {
                        if ($(element).hasClass('btn-primary')) {
                            $(element).removeClass('btn-primary');
                            $(element).removeClass('btn-selected');
                            $(element).addClass('btn-white');
                        }
                    })
                }
                $('#btn_'+type).click();
                var name = li.attr('data-name');
                var key = li.attr('data-key');
                var url = li.attr('data-url');
                var mediaId = li.attr('data-mediaid');
                if (type == 'view') {
                    $('#url').val(url);
                }
                else if (type == 'media_id') {
                    $('#media_id').val(mediaId);
                }
                else if (type == 'view_limited') {
                    $('#media_id').val(mediaId);
                }
                else {
                    $('#key').val(key);
                }
            });

            $('.btnDelete').unbind();
            $('.btnDelete').bind('click', function (event) {
                if ($(this).parent().parent().hasClass('first-menu')) {
                    if ($(this).parent().parent().find('.second-menu').length > 0) {
                        $.modalAlert('一级菜单下包含有二级菜单，不能直接删除一级菜单；请先删除二级菜单，再删除一级菜单。', 'warning');
                    }
                    else {
                        $(this).parent().parent().remove();
                    }
                }
                else {
                    $(this).parent().parent().remove();
                }
            });
        }

        function validData() {
            var result = true;
            var inputs = $.find('input:required');
            $.each(inputs, function (index, element) {
                if ($(element).val().trim() == '') {
                    result = false;
                    $(element).closest('.form-group').addClass('has-error');
                }
                //$(element).unbind();
                //$(element).bind('input', function () {
                //    if ($(element).val().trim() != '') {
                //        $(element).parent().parent().removeClass('has-error');
                //        $(element).parent().parent().addClass('has-success');
                //    }
                //})
            });
            return result;
        }
    </script>




    <script id="keyTemplate" type="text/html">
        <div class="form-group">
            <label class="col-sm-2 control-label">关键字</label>
            <div class="col-sm-10">
                <input id="key" type="text" class="form-control" required="required">
            </div>
        </div>
    </script>
    <script id="urlTemplate" type="text/html">
        <div class="form-group">
            <label class="col-sm-2 control-label">链接</label>
            <div class="col-sm-10">
                <input id="url" type="text" class="form-control" required="required">
            </div>
        </div>
    </script>                
    <script id="materialTemplate" type="text/html">
        <div class="form-group">
            <label class="col-sm-2 control-label">素材Id</label>
            <div class="col-sm-10">
                <div class="input-group">
                    <input id="media_id" type="text" class="form-control" required="required">
                    <span class="input-group-btn">
                        <button id="choose-material" type="button" class="btn btn-white" >
                            从素材库库中选择
                        </button>
                    </span>
                </div>
            </div>
        </div>
    </script>
    <script id="newsTemplate" type="text/html">
        <div class="form-group">
            <label class="col-sm-2 control-label">素材Id</label>
            <div class="col-sm-10">
                <div class="input-group">
                    <input id="media_id" type="text" class="form-control" required="required">
                    <span class="input-group-btn">
                        <button id="choose-news" type="button" class="btn btn-white">
                            从素材库库中选择
                        </button>
                    </span>
                </div>
            </div>
        </div>
    </script>
    <script id="nestableTemplate" type="text/html">
        {{each button as btn i}}
        <li class="dd-item dd-nodrag first-menu" data-id="" data-type="{{btn.type}}" data-name="{{btn.name}}" data-key="{{btn.key}}" data-url="{{btn.url}}" data-mediaid="{{btn.media_id}}">
            <div class="dd-handle">
                <button class="btn btn-xs btn-white pull-right btnDelete"><i class="fa fa-trash"></i> 删除</button>
                <button class="btn btn-xs btn-white pull-right btnEdit"><i class="fa fa-pencil"></i> 编辑</button>
                <button class="btn btn-xs btn-white pull-right btnAdd"><i class="fa fa-plus"></i> 新增</button>
                <span class="label label-info"><i class="fa fa-bars"></i></span>
                <span>{{btn.name}}</span>
            </div>
            {{if typeof(btn.sub_button) !='undefined'}}
            <ol class="dd-list">
                {{each btn.sub_button as subbtn j}}
                <li class="dd-item dd-nodrag second-menu" data-id="" data-type="{{subbtn.type}}" data-name="{{subbtn.name}}" data-key="{{subbtn.key}}" data-url="{{subbtn.url}}" data-mediaid="{{subbtn.media_id}}">
                    <div class="dd-handle">
                        <button class="btn btn-xs btn-white pull-right btnDelete"><i class="fa fa-trash"></i> 删除</button>
                        <button class="btn btn-xs btn-white pull-right btnEdit"><i class="fa fa-pencil"></i> 编辑</button>
                        <span class="label label-info"><i class="fa fa-bars"></i></span>
                        <span>{{subbtn.name}}</span>
                    </div>
                </li>
                {{/each}}
            </ol>
            {{else}}
            <ol class="dd-list"></ol>
            {{/if}}
        </li>
        {{/each}}
    </script>
    <script id="firstMenuTemplate" type="text/html">
        <li class="dd-item dd-nodrag first-menu" data-id="">
            <button data-action="collapse" type="button" style="display: block;">Collapse</button>
            <button data-action="expand" type="button" style="display: none;">Expand</button>
            <div class="dd-handle">
                <button class="btn btn-xs btn-white pull-right btnDelete"><i class="fa fa-trash"></i> 删除</button>
                <button class="btn btn-xs btn-white pull-right btnEdit"><i class="fa fa-pencil"></i> 编辑</button>
                <button class="btn btn-xs btn-white pull-right btnAdd"><i class="fa fa-plus"></i> 新增</button>
                <span class="label label-info"><i class="fa fa-bars"></i></span>
                <span></span>
            </div>
            <ol class="dd-list"></ol>
        </li>
    </script>
    <script id="secondMenuTemplate" type="text/html">
        <li class="dd-item dd-nodrag second-menu">
            <div class="dd-handle">
                <button class="btn btn-xs btn-white pull-right btnDelete"><i class="fa fa-trash"></i> 删除</button>
                <button class="btn btn-xs btn-white pull-right btnEdit"><i class="fa fa-pencil"></i> 编辑</button>
                <span class="label label-info"><i class="fa fa-bars"></i></span>
                <span></span>
            </div>
        </li>
    </script>
</body>
</html>
